package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.MsslyyBook;
import com.example.pojo.MsslyyCart;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.MsslyyCartMapper;
import com.example.pojo.MsslyyWishlist;
import com.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MsslyyCartService extends ServiceImpl<MsslyyCartMapper, MsslyyCart> {
    @Resource
    private MsslyyCartMapper msslyyCartMapper;
    @Resource
    private MsslyyBookService msslyyBookService;
    public List getCartById(Long id){
        QueryWrapper<MsslyyCart> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyCart> eq = queryWrapper.lambda().eq(MsslyyCart::getUserId, id);
        List<MsslyyCart> list = list(eq);
        List<MsslyyBook> books = msslyyBookService.list();
        List books2 =new ArrayList<>();
        books.forEach(e->{
            list.forEach(b->{
                if (e.getId()==b.getBookId()){
                    e.setAddTime(b.getCreateTime());
                    e.setCartAmount(b.getCartAmount());
                    books2.add(e);

                }
            });
        });

        return books2;
    }
    public int addCart(Long userId,Long bookId,Integer cartAmount){
        QueryWrapper<MsslyyCart> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyCart> eq = queryWrapper
                .lambda()
                .eq(MsslyyCart::getBookId, bookId)
                .eq(MsslyyCart::getUserId, userId);
        MsslyyCart one = getOne(eq);
        //没有这条购物车记录
        if (one==null){
            MsslyyCart msslyyCart = new MsslyyCart();
            msslyyCart.setBookId(bookId);
            msslyyCart.setUserId(userId);
            msslyyCart.setCartAmount(cartAmount);
            msslyyCart.setStatus(1);
            save(msslyyCart);
            return 1;
        }else {
            one.setCartAmount(one.getCartAmount()+cartAmount);
            updateById(one);
            return 0;
        }



    }


}
